package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.SnakeFeature;
import com.wildlife.springboot.mapper.service.ImageUploadService;
import com.wildlife.springboot.service.ISnakeFeatureService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/snakeFeature")
public class SnakeFeatureController {

    @Resource
    private ISnakeFeatureService snakeFeatureService;

    @Resource
    private ImageUploadService imageUploadService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody SnakeFeature snakeFeature){
        //新增或更新
        return Result.success(snakeFeatureService.saveOrUpdate(snakeFeature));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(snakeFeatureService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(snakeFeatureService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(snakeFeatureService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(snakeFeatureService.getById(id));
    }

    @GetMapping("/chineseName/{chineseName}")
    public Result findOne(@PathVariable String chineseName) {
        QueryWrapper<SnakeFeature> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chinese_name", chineseName);
        return Result.success(snakeFeatureService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String chineseName
    ) {
//        System.out.print("前端再次请求！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！");
        QueryWrapper<SnakeFeature> queryWrapper = new QueryWrapper<>();
        if (!"".equals(chineseName)) {
            queryWrapper.like("chinese_name", chineseName);
        }
//        if (!"".equals(email)) {
//            queryWrapper.like("email", email);
//        }
//        if (!"".equals(address)) {
//            queryWrapper.like("address", address);
//        }
        return Result.success(snakeFeatureService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<SnakeFeature> list = snakeFeatureService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("suborder", "亚目");
        writer.addHeaderAlias("section", "科");
        writer.addHeaderAlias("genus", "属");
        writer.addHeaderAlias("nickname", "学名");
        writer.addHeaderAlias("chineseName", "中文名");
        writer.addHeaderAlias("englishName", "英文名");
        writer.addHeaderAlias("authors", "作者");
        writer.addHeaderAlias("literatureResources", "物种名录来源");
        writer.addHeaderAlias("iucn", "IUCN红色名录IUCN Red List");
        writer.addHeaderAlias("internasalScale", "鼻间鳞 (对)");
        writer.addHeaderAlias("prefrontalScale", "前额鳞（对）");
        writer.addHeaderAlias("frontalScale", "额鳞");
        writer.addHeaderAlias("apicalScale", "顶鳞(对)");
        writer.addHeaderAlias("interparietal", "顶间鳞");
        writer.addHeaderAlias("supraorbitalScale", "眶上鳞(对)");
        writer.addHeaderAlias("nasalScale", "鼻鳞 (对)");
        writer.addHeaderAlias("buccalScale", "颊鳞(对)");
        writer.addHeaderAlias("preorbitalScale", "眶前鳞(对)");
        writer.addHeaderAlias("retroorbitalScale", "眶后鳞(对)");
        writer.addHeaderAlias("infraorbitalScale", "眶下鳞(对)");
        writer.addHeaderAlias("temporalScale", "颞鳞");
        writer.addHeaderAlias("snoutScale", "吻鳞");
        writer.addHeaderAlias("upperLipScale", "上唇鳞");
        writer.addHeaderAlias("chinScale", "颏鳞");
        writer.addHeaderAlias("labialScale", "下唇鳞");
        writer.addHeaderAlias("jawFilm", "颌片");
        writer.addHeaderAlias("abdominalScale", "腹鳞");
        writer.addHeaderAlias("analScale", "肛鳞");
        writer.addHeaderAlias("dorsalScale", "背鳞");
        writer.addHeaderAlias("caudalScale", "尾下鳞");
        writer.addHeaderAlias("backColor", "背部颜色");
        writer.addHeaderAlias("abdominalColor", "腹部颜色");
        writer.addHeaderAlias("maxillaryTeeth", "上颌齿");
        writer.addHeaderAlias("teeth", "前沟牙/后沟牙/管牙");
        writer.addHeaderAlias("dataSources", "数据来源");
        writer.addHeaderAlias("maleStandardLength", "标准体长/mm（雄性）");
        writer.addHeaderAlias("femaleStandardLength", "标准体长/mm（雌性）");
        writer.addHeaderAlias("unknowngenderStandardLength", "标准体长/mm（未知性别）");
        writer.addHeaderAlias("maleMaxLength", "最大体长/mm（雄性）");
        writer.addHeaderAlias("femaleMaxLength", "最大体长/mm（雌性）");
        writer.addHeaderAlias("unknowngenderMaxLength", "最大体长/mm（未知性别）");
        writer.addHeaderAlias("maleStandardTail", "标准尾长/mm（雄性）");
        writer.addHeaderAlias("femaleStandardTail", "标准尾长/mm（雌性）");
        writer.addHeaderAlias("unknowngenderStandardTail", "标准尾长/mm（未知性别）");
        writer.addHeaderAlias("dataSources1", "数据来源");
        writer.addHeaderAlias("dietSpecific", "食性（具体的）");
        writer.addHeaderAlias("dietCategory", "食性（类别）");
        writer.addHeaderAlias("dataSources2", "数据来源");
        writer.addHeaderAlias("predationMode", "捕食方式");
        writer.addHeaderAlias("reproductiveMode", "繁殖方式");
        writer.addHeaderAlias("eggCount", "窝卵数");
        writer.addHeaderAlias("eggSize", "卵大小（卵宽×卵长）/mm");
        writer.addHeaderAlias("dataSources3", "数据来源");
        writer.addHeaderAlias("activityTime", "成体活动时间");
        writer.addHeaderAlias("toxicity", "有无毒性");
        writer.addHeaderAlias("dataSources4", "数据来源");
        writer.addHeaderAlias("chineseEndemicSpecies", "是否中国特有种");
        writer.addHeaderAlias("islandEndemicSpecies", "是否岛屿特有种");
        writer.addHeaderAlias("area", "地理分布（中国）");
        writer.addHeaderAlias("foreignDistribution", "地理分布（国外）");
        writer.addHeaderAlias("dataSources5", "数据来源");
        writer.addHeaderAlias("adultHabitat", "成体生境");
        writer.addHeaderAlias("altitudeRange", "垂直分布/m");
        writer.addHeaderAlias("dataSources6", "数据来源");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("蛇类特征表", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("亚目", "suborder");
        reader.addHeaderAlias("科", "section");
        reader.addHeaderAlias("属", "genus");
        reader.addHeaderAlias("学名", "nickname");
        reader.addHeaderAlias("中文名", "chineseName");
        reader.addHeaderAlias("英文名", "englishName");
        reader.addHeaderAlias("作者", "authors");
        reader.addHeaderAlias("物种名录来源", "literatureResources");
        reader.addHeaderAlias("IUCN红色名录IUCN Red List", "iucn");
        reader.addHeaderAlias("鼻间鳞 (对)", "internasalScale");
        reader.addHeaderAlias("前额鳞（对）", "prefrontalScale");
        reader.addHeaderAlias("额鳞", "frontalScale");
        reader.addHeaderAlias("顶鳞(对)", "apicalScale");
        reader.addHeaderAlias("顶间鳞", "interparietal");
        reader.addHeaderAlias("眶上鳞(对)", "supraorbitalScale");
        reader.addHeaderAlias("鼻鳞 (对)", "nasalScale");
        reader.addHeaderAlias("颊鳞(对)", "buccalScale");
        reader.addHeaderAlias("眶前鳞(对)", "preorbitalScale");
        reader.addHeaderAlias("眶后鳞(对)", "retroorbitalScale");
        reader.addHeaderAlias("眶下鳞(对)", "infraorbitalScale");
        reader.addHeaderAlias("颞鳞", "temporalScale");
        reader.addHeaderAlias("吻鳞", "snoutScale");
        reader.addHeaderAlias("上唇鳞", "upperLipScale");
        reader.addHeaderAlias("颏鳞", "chinScale");
        reader.addHeaderAlias("下唇鳞", "labialScale");
        reader.addHeaderAlias("颌片", "jawFilm");
        reader.addHeaderAlias("腹鳞", "abdominalScale");
        reader.addHeaderAlias("肛鳞", "analScale");
        reader.addHeaderAlias("背鳞", "dorsalScale");
        reader.addHeaderAlias("尾下鳞", "caudalScale");
        reader.addHeaderAlias("背部颜色", "backColor");
        reader.addHeaderAlias("腹部颜色", "abdominalColor");
        reader.addHeaderAlias("上颌齿", "maxillaryTeeth");
        reader.addHeaderAlias("前沟牙/后沟牙/管牙", "teeth");
        reader.addHeaderAlias("数据来源", "dataSources");
        reader.addHeaderAlias("标准体长/mm（雄性）", "maleStandardLength");
        reader.addHeaderAlias("标准体长/mm（雌性）", "femaleStandardLength");
        reader.addHeaderAlias("标准体长/mm（未知性别）", "unknowngenderStandardLength");
        reader.addHeaderAlias("最大体长/mm（雄性）", "maleMaxLength");
        reader.addHeaderAlias("最大体长/mm（雌性）", "femaleMaxLength");
        reader.addHeaderAlias("最大体长/mm（未知性别）", "unknowngenderMaxLength");
        reader.addHeaderAlias("标准尾长/mm（雄性）", "maleStandardTail");
        reader.addHeaderAlias("标准尾长/mm（雌性）", "femaleStandardTail");
        reader.addHeaderAlias("标准尾长/mm（未知性别）", "unknowngenderStandardTail");
        reader.addHeaderAlias("数据来源", "dataSources1");
        reader.addHeaderAlias("食性（具体的）", "dietSpecific");
        reader.addHeaderAlias("食性（类别）", "dietCategory");
        reader.addHeaderAlias("数据来源", "dataSources2");
        reader.addHeaderAlias("捕食方式", "predationMode");
        reader.addHeaderAlias("繁殖方式", "reproductiveMode");
        reader.addHeaderAlias("窝卵数", "eggCount");
        reader.addHeaderAlias("卵大小（卵宽×卵长）/mm", "eggSize");
        reader.addHeaderAlias("数据来源", "dataSources3");
        reader.addHeaderAlias("成体活动时间", "activityTime");
        reader.addHeaderAlias("有无毒性", "toxicity");
        reader.addHeaderAlias("数据来源", "dataSources4");
        reader.addHeaderAlias("是否中国特有种", "chineseEndemicSpecies");
        reader.addHeaderAlias("是否岛屿特有种", "islandEndemicSpecies");
        reader.addHeaderAlias("地理分布（中国）", "area");
        reader.addHeaderAlias("地理分布（国外）", "foreignDistribution");
        reader.addHeaderAlias("数据来源", "dataSources5");
        reader.addHeaderAlias("成体生境", "adultHabitat");
        reader.addHeaderAlias("垂直分布/m", "altitudeRange");
        reader.addHeaderAlias("数据来源", "dataSources6");
        List<SnakeFeature> list = reader.readAll(SnakeFeature.class);
        snakeFeatureService.saveBatch(list);
        return true;
    }

    // 上传图片接口
    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = imageUploadService.uploadImage(file);
            // 返回相对路径而不是完整的本地文件路径
            return Result.success(url);
        } catch (Exception e) {
            return Result.fail("上传失败");
        }
    }
}
